import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)


import Index from '../views/Index'
import Login from '../views/Login'
import Register from '../views/Register'
import Home from '../views/Home'
import Page1 from '../views/Page1'
import UserForm from '../views/UserForm'
import UserInfo from '../views/UserInfo'
import NotFound from '../views/404'


const routes = [{
    path: '/',
    redirect: '/index'
  },
  {
    path: '/index',
    name: 'index',
    component: Index,
    children: [{
        path: '',
        redirect: '/home'
      },
      {
        path: '/home',
        component: Home,
        name: 'home'
      },
      {
        path: '/page1',
        component: Page1,
        name: 'page1'
      },
      {
        path: '/userForm',
        component: UserForm,
        name: 'userForm'
      },
      {
        path: '/userInfo',
        component: UserInfo,
        name: 'userInfo'
      },
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/register',
    name: 'register',
    component: Register
  },
  {
    path: '*',
    name: '404',
    component: NotFound
  },
]

const router = new VueRouter({
  routes,
  mode: 'history'
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLogin = localStorage.token ? true : false;
  if (to.path === '/login' || to.path === '/register') {
    next();
  } else {
    isLogin ? next() : next('/login');
  }
})

export default router;
